package com.hzjq.blast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.hzjq.core.Blast
import com.hzjq.core.bean.CapEntity
import com.hzjq.core.bean.ErrorResult
import com.hzjq.core.bean.LogBean
import com.hzjq.core.callback.Callback
import com.hzjq.core.callback.OnScanCapCallback
import com.hzjq.core.receive.ReceiverInterceptor
import com.hzjq.core.util.BlastLog
import com.hzjq.rxblast.callback.ChargeCallback
import com.hzjq.rxblast.callback.OnChargeClickListener
import com.hzjq.rxblast.ui.RegisterCapActivity
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : AppCompatActivity() {

    private val caps = arrayListOf<CapEntity>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        setContentView(R.layout.activity_main)
        Blast.getInstance().setDebug(true)

        Blast.getInstance().getChecker().start()


        mainOnlineScanCap.setOnClickListener {
            RxPermissions(this)
                .request(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (it) {
                        onScanCap()
                    }
                }
        }

        Blast.getInstance().addInterceptor(object : ReceiverInterceptor {
            override fun onInterceptor(stateCode: Int): Boolean {
                if (stateCode == 104) {
                    BlastLog.e("发生了短路")
                    clear()
                    return true
                }
                return false
            }

        })


        mScreenStatusReceiver = ScreenStatusReceiver()
        val screenStatusIF =  IntentFilter()
        screenStatusIF.addAction(Intent.ACTION_SCREEN_ON)
        screenStatusIF.addAction(Intent.ACTION_SCREEN_OFF)
        registerReceiver(mScreenStatusReceiver!!,screenStatusIF)

    }

    private fun clear() {
        Blast.getInstance()
            .getClearOccupyLoader()
            .clearOccupy(object : Callback<Boolean> {
                override fun onError(errorCode: ErrorResult) {

                }

                override fun onResult(t: Boolean) {

                }

                override fun onRetryCountChanged(retryCount: Int, action: String) {

                }
            })
    }

    private fun onScanCap() {
        if (caps.isNotEmpty()) {
            toRegister()
            return
        }
        caps.clear()
        Blast.getInstance().scanCap().onScanCap(object : OnScanCapCallback {

            override fun notifyVoltageElectricChanged(mVoltage: Float, mElectric: Float) {

            }

            override fun onError(errorCode: ErrorResult) {
                mainCapProgressAction.text = errorCode.errorAction
            }

            override fun onProgressChanged(progress: Int, total: Int, action: String) {
                mainCapProgressBar.progress = progress
                mainCapProgressBar.max = total
                mainCapProgressAction.text = action
            }

            override fun onResult(t: MutableList<CapEntity>) {
                t.forEach {
                    it.password = "00000000"
                    it.rowNumber = caps.size.toString()
                    it.holeNumber = caps.size.toString()
                    caps.add(it)
                    if (it.isScanEnd) {
                        it.delay = 1000
                        toRegister()
                    }
                }

            }

            override fun onRetryCountChanged(retryCount: Int, action: String) {
                mainCapProgressAction.text = "${action}($retryCount)"
            }

        })
    }

    private fun toRegister() {
        Blast.getInstance().setMaxSupportCapCount(caps.size)
        RegisterCapActivity.start(this@MainActivity, caps, object : OnChargeClickListener {
            override fun onChargeClick(
                context: Context,
                charge: ChargeCallback
            ): Boolean {
                charge.go()
                return true
            }
        })
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onLogEvent(log: LogBean) {
        Log.e("log", log.content)
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        unregisterReceiver(mScreenStatusReceiver)
    }

    private var mScreenStatusReceiver: ScreenStatusReceiver? = null


    class ScreenStatusReceiver : BroadcastReceiver() {
        private val SCREEN_ON = "android.intent.action.SCREEN_ON"
        private val SCREEN_OFF = "android.intent.action.SCREEN_OFF"
        override fun onReceive(context: Context, intent: Intent) {
            if (SCREEN_ON.equals(intent.getAction())) {
                Blast.getInstance().enableOtg(true)
            } else if (SCREEN_OFF.equals(intent.getAction())) {
                Blast.getInstance().enableOtg(false)
            }
        }
    }
}
